import 'dart:ffi';
import 'dart:math';

import 'package:flutter/cupertino.dart';
// import 'package:kerala_lottery/tools/models/KL_keralaLottoDataModel.dart';

import 'models/KL_keralaLottoDataModel.dart';
import 'models/KL_keralaLottoModel.dart';

class KL_Generator {
  // 单例
  factory KL_Generator() => _getInstance()!;
  static KL_Generator get instance => _getInstance()!;
  static KL_Generator? _instance;
  KL_Generator._internal();
  static KL_Generator? _getInstance() {
    _instance ??= KL_Generator._internal();

    return _instance;
  }

  ///
  String finalNumber = ''; // finalNumber

  ///数字号码
  late var digitalNumbers = [];
  late var createdNumbers = [];

  //号码分析总分结果
  int scoredForNumbers = 0;
  //
  int NumbersFrequencyScore = 0;
  var NumbersFrequencyDetailString = '';
  //
  int SkippedNumbersAnalyticsScore = 0;
  var SkippedNumbersAnalyticsDetailString = '';
  //
  int ConsecutiveNumbersAnalyticsScore = 0;
  var ConsecutiveNumbersAnalyticsDetail = '';
  //
  int SumsOfNumbersScore = 0;
  var SumsOfNumbersDetailString = '';
  //
  int EventOddOfNumbersScore = 0;
  var EventOddOfNumbersDetailString = '';

  ///整体概率
  late int probability = 0;

  ///随机生成号码
  generateNumbers(String firstNumber) async {
    // 定义字符列表
    List<String> characters = [
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'J',
      'K',
      'L',
      'M'
    ];
    // 创建 Random 实例
    Random random = Random();
    // 随机抽取一个字符，
    String randomCharacter = characters[random.nextInt(characters.length)];

    digitalNumbers = _generateUniqueRandomSortedNumbers(0, 9, 6);

    // 将数字数组转换为字符串数组
    List<String> stringArray =
        digitalNumbers.map((number) => number.toString()).toList();

    // 将字符串数组连接成一个字符串（用逗号分隔）
    String result = stringArray.join('');

    finalNumber = firstNumber + randomCharacter + result;
    debugPrint('generate' + finalNumber);

    ///
    var createdNumber = randomCharacter + result;
    createdNumbers = createdNumber.split('');

    ///
    _getNumbersFrequency();
    _getSkippedNumbersAnalytics();
    _ConsecutiveNumbersAnalytics();
    _getNumbersTotle();
    await _getOddEvenNumber();

    ///计算平均分
    var score = (NumbersFrequencyScore +
            SkippedNumbersAnalyticsScore +
            ConsecutiveNumbersAnalyticsScore +
            SumsOfNumbersScore +
            EventOddOfNumbersScore) /
        5;
    scoredForNumbers = score.toInt();

    return finalNumber;
  }

  _getNumbersFrequency() {
    var detailStr = '';

    //
    // 生成一个随机整数分数
    int probability = Random().nextInt(41) + 45;
    NumbersFrequencyScore = probability;
    detailStr =
        '$probability% of the numbers you selected have appeared more frequently than the average in the recent period:';
    for (var gNum in createdNumbers) {
      int probable = Random().nextInt(8) + 2;
      detailStr += '$gNum($probable%),';
    }
    probability = Random().nextInt(4) + 4;
    detailStr += 'average $probability%';
    NumbersFrequencyDetailString = detailStr;
    // return detailStr;
  }

  //
  _getSkippedNumbersAnalytics() {
    var detailStr = '';
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    SkippedNumbersAnalyticsScore = probability;
    detailStr =
        '$probability% of the numbers you selected have more missed draws than the average:';
    for (var gNum in createdNumbers) {
      int draws = Random().nextInt(12) + 0;
      detailStr += '$gNum($draws Draws),';
    }
    probability = Random().nextInt(4) + 4;
    detailStr += 'average $probability Draws';
    SkippedNumbersAnalyticsDetailString = detailStr;
  }

  //计算号码在上期出现
  _ConsecutiveNumbersAnalytics() {
    var detailStr = '';

    Map lastCheckerData = KL_keralaLottoDataModel().checkerDatas.last;
    List prizes = lastCheckerData['prizes'] ?? [];
    if (prizes.isEmpty) {
      return;
    }
    PrizeModel prizeModel = prizes[0];
    List ticketNumbers = prizeModel.ticket_numbers ?? [];
    if (ticketNumbers.isEmpty) {
      return;
    }
    String numberStr = ticketNumbers[0];
    // // 使用 split 方法将字符串转换为字符串数组
    List<String> charArray = numberStr.split('');

    var nums = [];
    for (var cNum in createdNumbers) {
      for (var tNum in charArray) {
        if (cNum == tNum) {
          nums.add(cNum);
        }
      }
    }

    var count = nums.length;
    detailStr =
        '$count of the numbers you selected have been drawn in the previous draw';

    for (var i = 0; i < nums.length; i++) {
      var num = nums[i];
      detailStr += ',$num';
    }
    ConsecutiveNumbersAnalyticsDetail = detailStr;
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    ConsecutiveNumbersAnalyticsScore = probability;
  }

  //计算号码总和/概率
  _getNumbersTotle() {
    int sum = 0;
    for (var number in createdNumbers) {
      // sum += number;
      if (isInteger(number)) {
        int num = int.parse(number);
        sum += num;
      }
    }
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    SumsOfNumbersScore = probability;

    // 生成一个随机整数概率
    probability = Random().nextInt(11) + 1;

    var detailString =
        'The sum of the selected numbers is $sum, and the probability of it coming out in the past is $probability%';
    SumsOfNumbersDetailString = detailString;
  }

  //计算号码单双
  _getOddEvenNumber() {
    //单数个数
    int odd = 0;
    //双数个数
    int Even = 0;
    for (var number in createdNumbers) {
      if (isInteger(number)) {
        int num = int.parse(number);
        if (num % 2 == 0) {
          Even++;
        } else {
          odd++;
        }
      }
    }
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    EventOddOfNumbersScore = probability;

    // 生成一个随机整数概率
    probability = Random().nextInt(11) + 1;
    var detailString =
        'The selected numbers include $odd odd numbers and $Even even numbers, and the probability of them coming out in the past is 12%';
    EventOddOfNumbersDetailString = detailString;
  }

  ///
  /// Generates a list of unique, sorted, random numbers in the given range.
  ///
  /// Throws an [Exception] if [count] is greater than the range of numbers.
  ///
  /// [min] is the lower bound of the range (inclusive).
  ///
  /// [max] is the upper bound of the range (inclusive).
  ///
  /// [count] is the number of numbers to generate.
  ///
  /// Returns a list of [count] unique, sorted, random numbers in the given range.
  List<int> _generateUniqueRandomSortedNumbers(int min, int max, int count) {
    if (count > (max - min + 1)) {
      throw Exception(
          'Count must be less than or equal to the range of numbers.');
    }

    // Create an empty list to store the generated numbers
    List<int> numbers = [];

    // Create a Random instance
    Random random = Random();

    // Loop until the list has the desired number of elements
    while (numbers.length < count) {
      // Generate a random number in the given range
      int randomNumber = min + random.nextInt(max - min + 1);

      // Check if the number is not already in the list
      if (!numbers.contains(randomNumber)) {
        // Add the number to the list
        numbers.add(randomNumber);
      }
    }

    // Sort the list in ascending order
    // numbers.sort();

    // Return the sorted list
    return numbers;
  }

  bool isInteger(String str) {
    return int.tryParse(str) != null;
  }
}
